/**
 * 日志中间件
 */
'use strict';

import * as Koa from 'koa';
import * as bunyan from 'bunyan';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import config from './config';
import { logService } from '../service/log';
const logPath = config.get('root') + config.get("log")['log_path'];
// 生成日志目录
mkdirp.sync(logPath);

const dbErrRBuf = new bunyan.RingBuffer({ limit: 100 });
dbErrRBuf.write = (record) => {
    console.log('日志写入数据库');
};
dbErrRBuf.writable = false;

// 判断日志对象是否存在
const obj: any = {};
if (!obj.log) {
    const logNamePrefix = logPath + config.get("log")['log_name'];
    obj.log = bunyan.createLogger({
        name: config.get("log")['log_name'],
        serializers: {
            req: reqSerializer,
            res: bunyan.stdSerializers.res,
            err: bunyan.stdSerializers.err
        },
        streams: [
            {
                level: 'info',
                stream: process.stdout
            },
            {
                type: 'rotating-file',
                level: 'error',
                path: logNamePrefix + '-' + 'error.log',
                period: '1d',   // daily rotation
                count: 7        // keep 7 back copies
            },
            {
                type: 'rotating-file',
                path: logNamePrefix + '-' + 'warn.log',
                level: 'warn',
                period: '1d',   // 一天为一个记录周期
                count: 3       // 记录保留天数
            },
            {
                type: 'rotating-file',
                path: logNamePrefix + '-' + 'fatal.log',
                level: 'fatal',
                period: '1d',   // 一天为一个记录周期
                count: 30        // 记录保留天数
            },
            {
                type: 'raw',
                level: 'fatal',
                stream: dbErrRBuf,
                reemitErrorEvents: true
            } as any,
            {
                type: 'raw',
                level: 'error',
                stream: dbErrRBuf,
                reemitErrorEvents: true
            } as any
        ]
    });

}

//req序列化
function reqSerializer(ctx: Koa.Context) {
    return {
        method: ctx.method,
        url: ctx.url,
        headers: ctx.headers,
        ip: ctx.headers['x-forwarded-for'] || ctx.ip || ctx.ips
    };
}

//填写日志
export const weritelog = (ctx: Koa.Context, reqtime: any) => {
    var contentM: any = {
        path: ctx.href,
        hostname: ctx.hostname,
        method: ctx.method,
        query: ctx.query,
        param: ctx.params,
        reqtime: reqtime,
        headers: ctx.headers,
        requestjson: ctx.request.body
    }
    if (ctx.method == "POST") {
        contentM.responsejson = ctx.response.body
    }

    var result = logService.createlog(contentM);

}

/**
 * 设置日志子进程，封装req
 */
function logChild(ctx: Koa.Context): {
    fatal(error: Error, format?: any, ...params: any[]): void
    // debug(error: Error): void,
    error(error: Error): void,
    info(): void,
    info(obj: any): void
} {
    let log = obj.log;
    return log.child({ req: ctx.request, res: ctx.res });
}

export default logChild;
//export let logger = logChild;
//export let koaLogger = Logger;

class DBRawStream {

}